package com.cmfi.service.impl.userRoleAuthImpl;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import com.cmfi.dao.userRoleAuthDao.UserDao;
import com.cmfi.domain.userRoleAuthEntity.LoginUser;
import com.cmfi.domain.userRoleAuthEntity.User;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
	@Autowired
	private UserDao userDao;

    @Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 查询用户信息
		User user = userDao.getFirstByUsername(username);
		// 如果没有查询到用户就抛出异常
		if (Objects.isNull(user)) {
			throw new RuntimeException("用户名或者密码错误");
		}
		// TODO 查询对应的权限信息
		List<String> authModules = userDao.getAuthorizeModulesByUserId(user.getId());
		authModules.removeIf(Objects::isNull);
		/***************************调试用，后续要删掉！！！！！！***************************************************/
		authModules.add("admin");
		authModules.add("test");
		
		// 把数据封装成UserDetails返回
		if (!authModules.isEmpty()) {
			return new LoginUser(user, authModules);
		} else {
			return new LoginUser(user, new ArrayList<String>());
		}
	}
}
